#!/usr/bin/python
#
# Copyright (c) 2008, Mathias Weber
# Copyright (c) 2008, Thomas Stauffer
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
#   list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
#   this list of conditions and the following disclaimer in the documentation
#   and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# $Id$

import sys
import random
import math
import time

"""
In this sample the unit tries to go to the target without colliding into a
building. The model with the level has nodes with names AI.001, AI.002, and
so on. This nodes are traversed to build an AI waypoint net.
Do not do this in the 21. century. Waypoints are a no go. Use walk meshes. They
offer new possibilities and often need less time to calculate than a waypoint
approach.

http://www.ai-blog.net/archives/000152.html
"""

"""
Is there no official maxfloat like maxint?
"""
sys.maxfloat = 1.7976931348623157e308

from pandac.PandaModules import CollisionHandlerQueue
from pandac.PandaModules import CollisionNode
from pandac.PandaModules import CollisionSegment
from pandac.PandaModules import CollisionTraverser
from pandac.PandaModules import LineSegs
from pandac.PandaModules import NodePath
from pandac.PandaModules import Point3

from direct.task import Task

import direct.directbase.DirectStart

base.setBackgroundColor(0.0, 0.0, 0.2)
base.disableMouse()
base.camLens.setNearFar(1.0, 100.0)
base.camLens.setFov(45.0)

camera.setPos(0.0, 0.0, 30.0)
camera.setHpr(0.0, -90.0, 0.0)

unitX, unitY = -8.0, -8.0
unit = loader.loadModel("woman")
unit.reparentTo(render)

def moveUnit(x, y):
    global unitX, unitY
    unitX += x
    unitY += y
    unit.setPos(unitX, unitY, 0.0)

moveUnit(0.0, 0.0)

targetX, targetY = 8.0, 3.0
target = loader.loadModel("man")
target.reparentTo(render)

def moveTarget(x, y):
    global targetX, targetY
    targetX += x
    targetY += y
    target.setPos(targetX, targetY, 0.0)

moveTarget(0.0, 0.0)

"""
The world VertexPool in this example is manually extended with a collide tag.

  <Collide> { polyset keep descend }
  <VertexPool> World {

In this example the AI nodes are also drawn.
"""

world = loader.loadModel("example-path")
world.reparentTo(render)

segment = CollisionSegment()
segmentNode = render.attachNewNode(CollisionNode("AI"))
segmentNode.node().addSolid(segment)
queue = CollisionHandlerQueue()
traverser = CollisionTraverser("AI")
traverser.addCollider(segmentNode, queue)

def isColliding(a, b):
    segment.setPointA(a)
    segment.setPointB(b)
    traverser.traverse(render)
    return queue.getNumEntries() > 0

net = []

"""
We draw this lines only to debug the waypoint net.
"""

lines = LineSegs()
lines.setColor(1.0, 0.0, 0.0, 1.0)

"""
This routine checks the path from A to B and later from B to A for every
combination of A and B. We need this information for the AI, but it would be
faster if we do the checks only once and fill the result into the list twice
manually. The list looks like:

[source-pos-1, [ [destination-index-1, distance-1], [destination-index-2, distance-2], ...] ],
[source-pos-2, ...
"""

connectionCount = 0
aiNodes = world.findAllMatches("*/AI*")
for src in range(aiNodes.getNumPaths()):
    destinations = []
    possrc = aiNodes[src].getPos()
    for dst in range(aiNodes.getNumPaths()):
        if src == dst:
            continue

        posdst = aiNodes[dst].getPos()

        """
        Throw away what is too far away. Needs fine tuning.
        """
        length = (possrc - posdst).length()
        if length > 10.0:
            continue

        """
        Now do an expensive collision check.
        """
        if isColliding(possrc, posdst):
            continue

        destinations += [ [dst, length] ]

        lines.moveTo(possrc.getX(), possrc.getY(), 3.0)
        lines.drawTo(posdst.getX(), posdst.getY(), 3.0)

        connectionCount += 1
    net += [ [possrc, destinations] ]

print "-" * 80
print "connections", connectionCount
print "-" * 80

linesNode = NodePath(lines.create())
linesNode.reparentTo(render)

"""
The goal list should contain a list of position our unit should pass.
"""

previousTime = 0.0
goalList = []

UNIT_SPEED = 4.0
CLOSE_ENOUGH = 0.1

def handleGoal(task):
    global previousTime, goalList

    """
    Seems like task.dt is not correct on high FPS (tested with 700+), neither is
    time.time() but time.time() sums up correctly at least. Have to test this
    once again.
    """

    currentTime = time.time()
    t = currentTime - previousTime
    previousTime = currentTime

    """
    If we have no goal we do not do anything.
    """
    if len(goalList) == 0:
        return Task.cont

    deltaX = goalList[0][0] - unitX
    deltaY = goalList[0][1] - unitY
    distance = math.sqrt(deltaX * deltaX + deltaY * deltaY)

    """
    If we are close enough we delete the current goal. We have a broblem here.
    Because our goal handling routine is tied to the frame rate of the
    application, it is possible that a unit never reachs its target. If the
    frame rate is to low, it is possible that the target always is passing the
    goal and never gets close enough. An idea: Create a direction vector before
    the movement and after the movement. If the two directions point in a
    opposite direction we have missed our target.
    """

    if distance < CLOSE_ENOUGH:
        del goalList[0]
        return Task.cont

    """
    Only 1 fps? As already written we need to care about this case more
    cleverly.
    """
    if t > 1.0:
        return Task.cont

    x = UNIT_SPEED * t * (deltaX / distance)
    y = UNIT_SPEED * t * (deltaY / distance)
    moveUnit(x, y)

    return Task.cont

taskMgr.add(handleGoal, "AI")

"""
Create an appropriate goal with a brute force search.
"""

def search(current, currentLength, all, allLength, dst, depth):
    src = current[-1]

    if (src in current[:-1]):
        return

    if (depth > 7):
        return

    if (src == dst):
        all += [ current ]
        allLength += [ currentLength ]
        return

    for destinations in net[src][1]:
        search(current + [destinations[0]], currentLength + destinations[1], all, allLength, dst, depth + 1)

def gotoTarget():
    global goalList

    posunit = Point3(unitX, unitY, 1.0)
    postarget = Point3(targetX, targetY, 1.0)

    timeStart = time.time()

    if isColliding(posunit, postarget):
        goalList = []

        """
        First search the nearest node. There should always be at least one
        possibility to reach one node. For the full path it is not always the
        best solution to go to the nearest node first. We do not do a collision
        check here, because we assume it that there is always a AI node without
        any collision, or else the level designer has done anything wrong.
        """

        distanceMin = sys.maxfloat
        for i in range(len(net)):
            pos = net[i][0]
            distance = (pos - posunit).length()
            if distance < distanceMin:
                distanceMin, fromnode = distance, i

        """
        Search node nearest to target. As for the first node, we assume that we
        can reach our target from the final waypoint without any collision.
        """

        distanceMin = sys.maxfloat
        for i in range(len(net)):
            pos = net[i][0]
            distance = (pos - postarget).length()
            if distance < distanceMin:
                distanceMin, tonode = distance, i

        """
        Brute force search from fromnode to tonode.
        """

        all = []
        allLength = []
        search([fromnode], 0.0, all, allLength, tonode, 0)

        print "-" * 80
        print "valid paths", len(all)
        print "-" * 80

        lengthMin = sys.maxfloat
        for i in range(len(allLength)):
            if allLength[i] < lengthMin:
                lengthMin, bestNode = allLength[i], i

        """
        Build list.
        """

        goalList += [ [net[fromnode][0].getX(), net[fromnode][0].getY()] ]

        for i in all[bestNode]:
            goalList += [ [net[i][0].getX(), net[i][0].getY()] ]

        goalList += [ [net[tonode][0].getX(), net[tonode][0].getY()] ]
        goalList += [ [targetX, targetY] ]


    else:
        goalList = [ [targetX, targetY] ]

    timeEnd = time.time()

    print "-" * 80
    print "pathfinding", timeEnd - timeStart, "s"
    print "-" * 80

base.accept("escape", sys.exit)
base.accept("a", render.analyze)
base.accept("o", base.oobe)
base.accept("l", render.ls)

base.accept("6", moveTarget, [0.5, 0.0])
base.accept("6-repeat", moveTarget, [0.5, 0.0])
base.accept("4", moveTarget, [-0.5, 0.0])
base.accept("4-repeat", moveTarget, [-0.5, 0.0])
base.accept("8", moveTarget, [0.0, 0.5])
base.accept("8-repeat", moveTarget, [0.0, 0.5])
base.accept("2", moveTarget, [0.0, -0.5])
base.accept("2-repeat", moveTarget, [0.0, -0.5])
base.accept("space", gotoTarget)

run()
